package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.exception.ParseAddressException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.BaiduMapUtil;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.business.entity.Banner;
import com.web.exiaodao.business.entity.TravelTable;
import com.web.exiaodao.business.repository.BannerRepository;
import com.web.exiaodao.business.repository.TravelTableRepository;
import com.web.exiaodao.business.service.TravelTableService;
import com.web.exiaodao.remote.vo.TravelTableVo;

@Service("TravelTableService")
@Transactional(readOnly = false)
public class TravelTableServiceImpl extends BaseService<TravelTable> implements TravelTableService {

	private static final Logger LOGGER = Logger.getLogger(TravelTableServiceImpl.class);

	@Autowired
	private TravelTableRepository travelTableRepository;
	@Autowired
	BannerRepository bannerRepository;
	
	/**
	 * 查询单条TravelTable信息
	 * //@param tId
	 * @return 返回单个TravelTable对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<TravelTable> findOne(Long modelId) throws BusinessException {
		TravelTable obj = new TravelTable();
		if(modelId != 0){
			obj = travelTableRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<TravelTable> xr = new XaResult<TravelTable>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
			LOGGER.info("后台----->查询单个实体----->TravelTable");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的TravelTable数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象TravelTable集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<TravelTable>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<TravelTable> page = travelTableRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), TravelTable.class), pageable);
		XaResult<Page<TravelTable>> xr = new XaResult<Page<TravelTable>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->TravelTable");
		return xr;
	}

	/**
	 * 分页查询状态status的TravelTable数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象TravelTable集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<TravelTable>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<TravelTable> page = travelTableRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), TravelTable.class), pageable);
		XaResult<Page<TravelTable>> xr = new XaResult<Page<TravelTable>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->TravelTable");
		return xr;
	}

	/**
	 * 保存TravelTable信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<TravelTable> saveOrUpdate(TravelTableVo model) throws BusinessException {
		XaResult<TravelTable> xr = new XaResult<TravelTable>();
		//根据游玩名称查询数据
		TravelTable  travelName = travelTableRepository.findByTravelItemNameAndStatusNot(model.getTravelItemName(), XaConstant.Status.delete);
		TravelTable obj = null;
		if(XaUtil.isNotEmpty(model.getId())){//更新游玩项目
			obj = travelTableRepository.findOne(model.getId());
			if(travelName!=null && obj.getId()!=travelName.getId()){
				xr.error("游玩项目名称重复");
				return xr;
			}
			//如果地址没有，则不解析经纬度，否则解析经纬度
			if(!obj.getTravelItemAddress().equals(model.getTravelItemAddress())){
				this.setStoreLngAndLat(obj,model.getTravelItemAddress());
			}
		}else{//新增游玩项目
			if(travelName!=null){
				xr.error("游玩项目名称重复");
				return xr;
			}
			obj = new TravelTable();
			//解析经纬度
			this.setStoreLngAndLat(obj,model.getTravelItemAddress());
			
		}
		
	    obj.setTravelItemName(XaUtil.isNotEmpty(model.getTravelItemName()) ? model.getTravelItemName() : obj.getTravelItemName());
	    obj.setTravelBrief(XaUtil.isNotEmpty(model.getTravelBrief()) ? model.getTravelBrief() : obj.getTravelBrief());
	    obj.setTravelItemPrice(XaUtil.isNotEmpty(model.getTravelItemPrice()) ? model.getTravelItemPrice() : obj.getTravelItemPrice());
	    obj.setTravelItemAddress(XaUtil.isNotEmpty(model.getTravelItemAddress()) ? model.getTravelItemAddress() : obj.getTravelItemAddress());
	    obj.setLng(XaUtil.isNotEmpty(model.getLng()) ? model.getLng() : obj.getLng());
	    obj.setLat(XaUtil.isNotEmpty(model.getLat()) ? model.getLat() : obj.getLat());
	    obj.setTravelItemTelephone(XaUtil.isNotEmpty(model.getTravelItemTelephone()) ? model.getTravelItemTelephone() : obj.getTravelItemTelephone());
	    obj.setTravelItemType(XaUtil.isNotEmpty(model.getTravelItemType()) ? model.getTravelItemType() : obj.getTravelItemType());
	    obj.setRoute(XaUtil.isNotEmpty(model.getRoute()) ? model.getRoute() : obj.getRoute());
	    obj.setCost(XaUtil.isNotEmpty(model.getCost()) ? model.getCost() : obj.getCost());
	    obj.setSlogan(XaUtil.isNotEmpty(model.getSlogan()) ? model.getSlogan() : obj.getSlogan());
	    obj.setSort(XaUtil.isNotEmpty(model.getSort()) ? model.getSort() : obj.getSort());
	    obj.setClickCont(obj.getClickCont());
	    obj.setMinGroupPeople(XaUtil.isNotEmpty(model.getMinGroupPeople()) ? model.getMinGroupPeople() : obj.getMinGroupPeople());
	    obj.setPlanStartTime(XaUtil.isNotEmpty(model.getPlanStartTime()) ? model.getPlanStartTime() : obj.getPlanStartTime());
	    obj.setReservationPrice(XaUtil.isNotEmpty(model.getReservationPrice()) ? model.getReservationPrice() : obj.getReservationPrice());
	    obj = travelTableRepository.save(obj);
		if(XaUtil.isNotEmpty(model.getId())){
			List<Banner> b = bannerRepository.findByobjectIdAndTypeAndStatusNot(model.getId(), JConstant.BannerType.TRAVEL, XaConstant.Status.delete);
			if(XaUtil.isEmpty(b)){
				//新增上传游学图片
				if(XaUtil.isNotEmpty(model.getIntro()) || XaUtil.isNotEmpty(model.getTourImg())){
					String sql = "INSERT INTO `tb_xa_banner` (picurl,TYPE,intro,object_id,create_time) VALUES ('"+model.getTourImg()+"',"+JConstant.BannerType.TRAVEL+",'"+model.getIntro()+"',"+obj.getId()+",now())";
					this.update(sql);
				}
			}else{
				//修改banner
				if(XaUtil.isNotEmpty(model.getIntro()) || XaUtil.isNotEmpty(model.getTourImg())){
					String sql = "UPDATE `tb_xa_banner` SET picurl = '"+model.getTourImg()+"',intro = '"+model.getIntro()+"' WHERE object_id = "+model.getId()+"  AND TYPE = "+JConstant.BannerType.TRAVEL+" AND STATUS<>"+XaConstant.Status.delete;
					this.update(sql);
				}
			}
		}else{
			if(XaUtil.isNotEmpty(model.getIntro()) || XaUtil.isNotEmpty(model.getTourImg())){
				String sql = "INSERT INTO `tb_xa_banner` (picurl,TYPE,intro,object_id,create_time) VALUES ('"+model.getTourImg()+"',"+JConstant.BannerType.TRAVEL+",'"+model.getIntro()+"',"+obj.getId()+",now())";
				this.update(sql);
			}
		}
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 根据地址查询经纬度
	 * @param travel
	 * @param travelAdd
	 */
	private void setStoreLngAndLat(TravelTable travel, String travelAdd) {
		//根据地址查询经纬度
		Map<String,String> map=BaiduMapUtil.getGeocoderLatitude(travelAdd);
		if(map==null){
			throw new ParseAddressException("地址解析异常,请重新输入地址");
		}
		String lng=map.get("lng");
		String lat=map.get("lat");
		if(XaUtil.isEmpty(lng)||XaUtil.isEmpty(lat)){
			throw new ParseAddressException("地址解析异常,请重新输入地址");
		}
		travel.setLng(Double.valueOf(lng));
		travel.setLat(Double.valueOf(lat));
	}
	
	/**
	 * 修改TravelTable状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回TravelTable对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<TravelTable> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<TravelTable> xr = new XaResult<TravelTable>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				TravelTable obj = travelTableRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = travelTableRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}

	//查询游学列表
	@Override
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Page<TravelTableVo>> findTravelTableList(Pageable pageable,
			Map<String, Object> filterParams) throws BusinessException {
		StringBuffer sql = new StringBuffer("SELECT t.id,t.travel_item_name,t.slogan,t.travel_brief,t.travel_item_price,t.travel_item_address,t.lng,t.lat,t.travel_item_telephone,t.travel_item_type,t.route,t.cost,t.create_time,b.`picurl`,b.`intro`,t.`sort`,t.click_cont,t.min_group_people,t.plan_start_time,t.reservation_price ");
		sql.append("FROM `tb_xa_traveltable` t ");
		sql.append("LEFT JOIN `tb_xa_banner` b ON t.id = b.object_id WHERE b.type = ").append(JConstant.BannerType.TRAVEL).append(" ");
		sql.append(" AND t.status<>").append(XaConstant.Status.delete);
		sql.append(" AND b.status<>").append(XaConstant.Status.delete);
		StringBuffer sql1 = new StringBuffer("select count(*) ");
		sql1.append("FROM `tb_xa_traveltable` t ");
		sql1.append("LEFT JOIN `tb_xa_banner` b ON t.id = b.object_id WHERE b.type = ").append(JConstant.BannerType.TRAVEL).append(" ");
		sql1.append(" AND t.status<>").append(XaConstant.Status.delete);
		sql1.append(" AND b.status<>").append(XaConstant.Status.delete);
		//查询条件
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_TravelItemName"))){
			sql.append(" AND t.travel_item_name ").append(" like '%").append(filterParams.get("LIKE_TravelItemName")).append("%' ");
			sql1.append(" AND t.travel_item_name ").append(" like '%").append(filterParams.get("LIKE_TravelItemName")).append("%' ");
		}
		if(XaUtil.isNotEmpty(filterParams.get("EQ_TravelItemType"))){
			sql.append(" AND t.travel_item_type= ").append(filterParams.get("EQ_TravelItemType")).append(" ");
			sql1.append(" AND t.travel_item_type= ").append(filterParams.get("EQ_TravelItemType")).append(" ");
		}
		sql.append(" ORDER BY t.sort ASC,t.click_cont DESC,t.create_time desc");
		sql1.append(" ORDER BY t.sort ASC,t.click_cont DESC,t.create_time desc");
		List<Object[]> objs = this.query(sql.toString(), pageable.getPageNumber()*pageable.getPageSize(), pageable.getPageSize());
		List<TravelTableVo> vos = new ArrayList<TravelTableVo>();
		for (Object[] obj : objs) {
			TravelTableVo vo = new TravelTableVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			vo.setTravelItemName(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			vo.setSlogan(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
			vo.setTravelBrief(XaUtil.isEmpty(obj[3])?"":obj[3].toString());
			vo.setTravelItemPrice(XaUtil.isEmpty(obj[4])?0:Double.valueOf(obj[4].toString()));
			vo.setTravelItemAddress(XaUtil.isEmpty(obj[5])?"":obj[5].toString());
			vo.setLng(Double.valueOf(XaUtil.isEmpty(obj[6])?"":obj[6].toString()));
			vo.setLat(Double.valueOf(XaUtil.isEmpty(obj[7])?"":obj[7].toString()));
			vo.setTravelItemTelephone(XaUtil.isEmpty(obj[8])?"":obj[8].toString());
			vo.setTravelItemType(XaUtil.isEmpty(obj[9])?1:Integer.valueOf(obj[9].toString()));
			vo.setRoute(XaUtil.isEmpty(obj[10])?"":obj[10].toString());
			vo.setCost(XaUtil.isEmpty(obj[11])?"":obj[11].toString());
			vo.setCreateTime(XaUtil.isEmpty(obj[12])?"":obj[12].toString());
			if(XaUtil.isEmpty(obj[13])){
				vo.setTourList(null);
			}else{
				String imgs = XaUtil.isEmpty(obj[13])?"":obj[13].toString();
				String[] arr = imgs.split(",");
				List<String> list = java.util.Arrays.asList(arr);
				vo.setTourList(list);
			}
			vo.setIntro(XaUtil.isEmpty(obj[14])?"":obj[14].toString());
			vo.setSort(XaUtil.isEmpty(obj[15])?0:Long.valueOf(obj[15].toString()));
			vo.setClickCont(XaUtil.isEmpty(obj[16])?0:Long.valueOf(obj[16].toString()));
			vo.setMinGroupPeople(XaUtil.isEmpty(obj[17])?0:Integer.valueOf(obj[17].toString()));
			vo.setPlanStartTime(XaUtil.isEmpty(obj[18])?"":obj[18].toString());
			vo.setReservationPrice(XaUtil.isEmpty(obj[19])?0:Double.valueOf(obj[19].toString()));
			vos.add(vo);
		}
		List<Object[]> obj1=this.query(sql1.toString(), null, null);
		int count=Integer.parseInt(obj1.get(0)+"");	
		Page<TravelTableVo> page= new MyPage<TravelTableVo>(pageable.getPageNumber(),pageable.getPageSize(),vos,count);
		XaResult<Page<TravelTableVo>> xr=new XaResult<Page<TravelTableVo>>();
		xr.setObject(page);
		return xr;
	}

	//根据ID查询游学
	@Override
	@Transactional(rollbackFor = Exception.class)
	public XaResult<TravelTableVo> findTravelTableById(Long modelId)
			throws BusinessException {
		TravelTable obj = new TravelTable();
		TravelTableVo vo = new TravelTableVo();
		vo.setTravelTable(obj);
		if(modelId != 0){
			obj = travelTableRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
			List<Banner> b = bannerRepository.findByobjectIdAndTypeAndStatusNot(modelId, JConstant.BannerType.TRAVEL, XaConstant.Status.delete);
			if(XaUtil.isNotEmpty(b)){
				String imgs = b.get(0).getPicurl();
				String[] arr = imgs.split(",");
				List<String> list = java.util.Arrays.asList(arr);
				vo.setTourList(list);
				vo.setIntro(b.get(0).getIntro());
			}
			vo.setTravelTable(obj);
		}
		XaResult<TravelTableVo> xr = new XaResult<TravelTableVo>();
		if (XaUtil.isNotEmpty(vo)) {
			xr.setObject(vo);
			LOGGER.info("后台----->查询单个实体----->TravelTable");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	@Override
	public XaResult<TravelTable> saveOrUpdate(TravelTable t)
			throws BusinessException {
		// TODO Auto-generated method stub
		return null;
	}
	
}
